<template>
  <el-drawer :title="title" :visible.sync="open" size="60%" append-to-body>
    <div class="drawer-content">
      <el-row>

        <el-descriptions class="margin-top" title="搜索客户" :column="3" border>
          <template slot="extra">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                     label-width="68px">
              <el-form-item label="" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入姓名"
                  clearable
                />
              </el-form-item>
              <el-form-item label="" prop="tel">
                <el-input
                  v-model="queryParams.tel"
                  placeholder="请输入客户电话"
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type="primary"  size="mini" @click="handleRowClick(entity)">确定</el-button>
              </el-form-item>
            </el-form>

          </template>
          <el-descriptions-item label="客户姓名" style="width: 33%">
            {{ entity.name}}
          </el-descriptions-item>
          <el-descriptions-item label="手机号" style="width: 33%">
            {{ entity.tel}}
          </el-descriptions-item>

          <el-descriptions-item label="客户状态" style="width: 33%">
              <dict-tag :options="dict.type.customer_status" :value="entity.customerStatus"/>

          </el-descriptions-item>
          <el-descriptions-item label="星级" style="width: 33%">
              <dict-tag :options="dict.type.level_type" :value="entity.level"/>
          </el-descriptions-item>
          <el-descriptions-item label="备注" style="width: 66%" >

            <div class="messageCard" v-html="entity.bz">
            </div>
          </el-descriptions-item>
        </el-descriptions>
<!--        <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange"-->
<!--                  height="100px" border @row-click="handleRowClick">-->
<!--          <el-table-column type="selection" width="55" align="center"/>-->
<!--          <el-table-column label="姓名" align="center" prop="name" width="80px"/>-->
<!--          <el-table-column label="客户电话" align="center" prop="tel" width="100px"/>-->
<!--          <el-table-column label="星级" align="center" prop="level" width="60px">-->
<!--            <template slot-scope="scope">-->
<!--              <dict-tag :options="dict.type.level_type" :value="scope.row.level"/>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="客户状态" align="center" prop="customerStatus" width="100px">-->
<!--            <template slot-scope="scope">-->
<!--              <dict-tag :options="dict.type.customer_status" :value="scope.row.customerStatus"/>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="备注" align="center">-->
<!--            <template slot-scope="scope">-->
<!--              <div class="messageCard" v-html="scope.row.bz">-->
<!--              </div>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->
<!--      -->
      </el-row>
      <div class="main-panel">
      <div class="panel">
        <div class="title">客户进件</div>
        <div class="content">
        <!-- 添加或修改再审件对话框 -->
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户姓名" prop="customerName">
                <el-input v-model="this.customer.customerName" placeholder="请输入客户姓名" disabled/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同号" prop="contractNum">
                <el-input v-model="form.contractNum" placeholder="请输入合同号"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="进件银行" prop="inBank">
                <el-select v-model="form.inBank" placeholder="请选择进件银行" clearable>
                  <el-option
                    v-for="dict in this.channelList"
                    :key="dict.id"
                    :label="dict.name"
                    :value="dict.id"
                  />
                </el-select>
                <!--                  <el-input v-model="form.inBank" placeholder="请输入进件银行" />-->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="进件日期" prop="inTime">
                <el-date-picker clearable
                                v-model="form.inTime"
                                type="date"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择进件日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="进件额度" prop="quotaApply">
                <el-input type="number" v-model="form.quotaApply" placeholder="请输入进件额度">
                  <i slot="suffix" style="font-style: normal; margin-right: 10px"> 元</i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="费率" prop="feerate">
                <el-input v-model="form.feerate" placeholder="请输入费率">
                  <i slot="suffix" style="font-style: normal; margin-right: 10px"> %</i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单件类型" prop="singletype">
                <el-select v-model="form.singletype" placeholder="请选择单件类型" clearable>
                  <el-option
                    v-for="dict in dict.type.singletype"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="渠道经理" prop="channelManage">
                <el-input v-model="form.channelManage" placeholder="请输入渠道经理"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收款账户" prop="payeeType">
                <el-select v-model="form.payeeType" placeholder="请选择收款账户" clearable>
                  <el-option
                    v-for="dict in dict.type.payee_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- :limit="4"
                           :fileTypeRegx="/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/"
                           accept=".JPG,.PNG,.jpg,.png"      -->
          <el-form-item label="合同" prop="htList">
            <upload-file ref="htUpload"
                         v-model="form.htList"
                         multiple
                         :fileSize="5120"
                         pathPrefix="siteManage"></upload-file>
          </el-form-item>
          <el-form-item label="金额配置">
            <el-radio-group v-model="form.disType" @change="disTypeChange(form.disType)">
              <el-radio
                v-for="dict in disTypeList"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="合作单" v-if="true">
            <div class="serve-person">
              <div class="serve-person-form-item" v-for="(item, index) in form.cooperateList" :key="item.key">
                <div class="item-op-icon" v-show="form.cooperateList.length > 1"
                     @click="removeCooperate(index)">
                  <img class="item-delete-icon" src="@/assets/project/icon-minus.png" alt="">
                </div>
                <div class="item-form-box dialog-form" :style="{ '--form-item-width': '50px' }">
                  <el-form-item label="人员" :prop="`cooperateList.${index}.userId`" label-width="50px" :rules="{
                      required: true, message: '人员不能为空', trigger: 'blur'
                    }">
                    <el-select v-model="item.userId" placeholder="请选择">
                      <el-option v-for="dict in userList" :key="dict.userId" :label="dict.userName"
                                 :value="dict.userId"
                                 :disabled="form.cooperateList.some(i => i.userId == dict.userId)"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="item-form-box dialog-form" :style="{ '--form-item-width': '50px' }" v-if="form.disType == '1'">
                  <el-form-item label="比例" :prop="`cooperateList.${index}.ratio`" label-width="50px" :rules="{
                      required: true, message: '比例不能为空', trigger: 'blur'
                    }">
                    <el-input-number v-model="item.ratio" :min="0"
                                     :max="9999999" :controls="false" placeholder="请输入比例">
                    </el-input-number>
                    <span> %</span>
                  </el-form-item>
                </div>
                <div class="item-form-box dialog-form" :style="{ '--form-item-width': '50px' }" v-if="form.disType == '2'">
                  <el-form-item label="金额" :prop="`cooperateList.${index}.ratio`" label-width="50px" :rules="{
                      required: true, message: '金额不能为空', trigger: 'blur'
                    }">
                    <el-input-number v-model="item.ratio" :min="0"
                                     :max="99999999" :controls="false" placeholder="请输入金额">
                    </el-input-number>
                    <span> 元</span>
                  </el-form-item>
                </div>
              </div>
              <div class="serve-person-form-item" @click="addCooperate">
                <div class="add-btn">
                  <img class="add-btn-icon" src="@/assets/project/icon-add.png" alt="">
                  <span class="add-icon-text">增加</span>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>

        </div>
      </div>
      </div>
    </div>

    <div class="pop-footer">
      <el-button size="small" type="primary" @click="submitForm">保 存</el-button>
      <el-button size="small" @click="cancel">取 消</el-button>
    </div>
  </el-drawer>
</template>

<script>
import {loadParentOrg} from "@/api/customer/customer";
import {addRevieweInfo, customerList} from "@/api/customer/revieweInfo"
import uploadFile from '@/components/ImageUpload'
import {channelList} from "@/api/channel/channelInfo";
import {getUserList} from "@/api/customerPool/customerPool";
import customer from "@/views/customer";

export default {
  name: "RevieweCustomer",
  dicts: ['payee_type', 'singletype', 'level_type', 'customer_status'],
  components: {
    uploadFile
  },
  data() {
    // 上传图片验证
    const picturesValid = (rule, value, callback) => {
      if (
        value.length === 0 ||
        (value.length && value.every((el) => el.delFlag === '1'))
      ) {
        callback(new Error('图片不能为空'))
      } else {
        callback()
      }
    }
    return {
      disTypeList: [
        {
        "value": "1",
        "label": "比例"
        },
        {
          "value": "2",
          "label": "指定金额"
        }
      ],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户信息表格数据
      customerList: [],
      entity: {},
      // 弹出层标题
      title: "签约进件",
      // 是否显示弹出层
      open: false,
      // 省级地址
      provinceList: [],
      // 市区地址
      searchCityList: [],
      // 区县
      searchCountyList: [],
      // 市区地址
      formCityList: [],
      // 区县
      formCountyList: [],

      // 渠道信息
      channelList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1,
        name: undefined,
        tel: undefined,
        level: undefined,
        loanType: undefined,
        age: undefined,
        sex: undefined,
        label: undefined,
        education: undefined,
        house: undefined,
        car: undefined,
        warranty: undefined,
        insurance: undefined,
        fund: undefined,
        salary: undefined,
        applyMoney: undefined,
        province: undefined,
        city: undefined,
        county: undefined,
        manager: undefined,
        customerStatus: undefined,
        companyStatus: undefined,
        distributeDeptId: undefined,
        share: undefined,
        source: undefined,
        dataSource: undefined,
        vip: undefined,
        taskId: undefined,
        createDate: undefined,
        bz: undefined,
        htList: []
      },
      // customerPull 客户拉取   deptPull 部门直接拉取
      type: "",
      // 表单参数
      form: {
        id: undefined,
        customerId: undefined,
        customerName: undefined,
        userId: undefined,
        userName: undefined,
        deptId: undefined,
        contractNum: undefined,
        feerate: undefined,
        quotaApply: undefined,
        inBank: undefined,
        inTime: undefined,
        singletype: undefined,
        status: undefined,
        approveQuota: undefined,
        approveTime: undefined,
        getQuota: undefined,
        sincerityFee: undefined,
        channelFee: undefined,
        revenue: undefined,
        payee: undefined,
        payeeType: undefined,
        payeeTime: undefined,
        bank: undefined,
        percentage: undefined,
        confirm: undefined,
        confirmtime: undefined,
        paybacktime: undefined,
        channelManage: undefined,
        deadline: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        htList: [],
        cooperateList: [
          {
            userId: this.$store.state.user.user.userId,
            deptId: this.$store.state.user.user.deptId,
            ratio: 100,
            id: undefined,
            key: 1
          }]
      },
      // 表单校验
      rules: {
        feerate: [
          {required: true, message: "费率不能为空", trigger: "blur"}
        ],
        inBank: [
          {required: true, message: "进件银行不能为空", trigger: "blur"}
        ],
        quotaApply: [
          {required: true, message: "进件额度不能为空", trigger: "blur"}
        ],
        inTime: [
          {required: true, message: "进件日期不能为空", trigger: "blur"}
        ],
        singletype: [
          {required: true, message: "单件不能为空", trigger: "blur"}
        ],
        payeeType: [
          {required: true, message: "收款账户不能为空", trigger: "blur"}
        ],
        // bank: [
        //   {required: true, message: "收款银行不能为空", trigger: "blur"}
        // ],
        channelManage: [
          {required: true, message: "渠道经理不能为空", trigger: "blur"}
        ],
        htList: [
          {
            required: true,
            message: "合同不能为空",
          }
        ],
      },
      customer: {
        customerId: null,
        customerName: null,
        taskId: null
      },
      userList: []
    };
  },
  created() {
    // this.getList();
    this.channelListInit();
    this.loadPOrg('0', 0, 's')
    this.reset()
  },
  methods: {
    // 合作单类型 调整
    disTypeChange(newValue) {
      console.log("进来了：" + newValue);
      this.form.cooperateList.forEach(it => {
        it.ratio = '';
      })
    },

    /** 获取用户信息 */
    getUserInfoList() {
      const query = {
        type: "1"
      }
      getUserList(query).then(response => {
        this.userList = response.data;
      })
    },

    // 新增服务对象
    addCooperate() {
      console.log("进来了")
      this.form.cooperateList.push({
        id: undefined,
        deptId: undefined,
        userId: undefined,
        ratio: undefined,
        key: Date.now()
      })
    },

    // 移除信息
    removeCooperate(index) {
      this.form.cooperateList.splice(index, 1);
    },

    channelListInit() {
      channelList().then(resp => {
        this.channelList = resp.data;
      })
    },
    // uploadUpdate() {
    //   this.$refs['form'].validateField('htList') // 此行单独校验form表单下的图片表单项
    // },

    /** 打开弹窗按钮 */
    openDialog(type) {
      this.type = type;
      this.open = true;
      this.resetQuery();
      this.getUserInfoList()
      this.reset();
      this.resetForm("queryForm");
    },
    /** 加载组织 **/
    loadPOrg(parentId, level, type) {
      loadParentOrg(parentId).then(response => {
        if (level == '0') {
          this.provinceList = response.data
        } else if (level == '1') {
          if (type === 's') {
            this.searchCityList = response.data
          } else {
            this.formCityList = response.data
          }
        } else {
          if (type == 's') {
            this.searchCountyList = response.data
          } else {
            this.formCountyList = response.data
          }
        }
      })
    },
    getChildren(parentId, level, type) {
      this.clearSelect(level, type)
      this.loadPOrg(parentId, level, type)
    },

    clearSelect(level, type) {
      if (type == 's') {
        if (level == '1') {
          this.searchCityList = []
          this.queryParams.city = ''
        }
        this.queryParams.county = ''
        this.searchCountyList = []
      } else {
        if (level == '1') {
          this.formCityList = []
          this.form.city = ''
        }
        this.form.county = ''
        this.formCountyList = []
      }
    },
    /** 查询客户信息列表 */
    getList() {
      this.loading = false;
      customerList(this.queryParams).then(response => {
        this.customerList = response.rows;
        if(this.customerList.length>0){
          this.entity = this.customerList[0]
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm() {
      // 获取数据
      //this.form.htList = JSON.stringify(this.form.htList)
      let list = this.form.htList
      let strs = [];
      for (let i in list) {
        let str = list[i];
        str.url = str.url.replace(process.env.VUE_APP_BASE_API, "")
        strs.push(str)
      }
      this.form.htList = strs

      // 处理部门信息
      this.form.cooperateList.forEach(it => {
        it.deptId = this.userList.find(item => item.userId == it.userId)?.deptId
      })

      // 保存表单数据
      this.$refs["form"].validate(valid => {
          this.buttonLoading = true;
          const data = {
            ...this.form,
            ...this.customer
          }
          if (valid) {
            addRevieweInfo(data).then(res => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              if (this.$parent.getList) {
                this.$parent.getList();
              }
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      )
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        customerId: undefined,
        customerName: undefined,
        userId: undefined,
        userName: undefined,
        deptId: undefined,
        contractNum: undefined,
        feerate: undefined,
        quotaApply: undefined,
        inBank: undefined,
        inTime: undefined,
        singletype: undefined,
        status: undefined,
        approveQuota: undefined,
        approveTime: undefined,
        getQuota: undefined,
        sincerityFee: undefined,
        channelFee: undefined,
        revenue: undefined,
        payee: undefined,
        payeeType: undefined,
        payeeTime: undefined,
        bank: undefined,
        percentage: undefined,
        confirm: undefined,
        confirmtime: undefined,
        paybacktime: undefined,
        channelManage: undefined,
        deadline: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        htList: [],
        disType: "1",
        // 初始化为 100
        cooperateList: [
          {
            userId: this.$store.state.user.user.userId,
            deptId: this.$store.state.user.user.deptId,
            ratio: 100,
            id: undefined,
            key: 1
          }
        ]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.form.vip) {
        this.form.vip = undefined;
      }
      this.searchCityList = [];
      this.searchCountyList = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // handleRowClick(row) {
    //   this.customer.customerId = row.id
    //   this.customer.customerName = row.name
    // },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      const customerId = this.ids[this.ids.length - 1]
      if (customerId) {
        const obj = selection.find(item => item.id === customerId)
        //if (this.customer) {
        //  Object.keys(this.customer).forEach(key => {
        //    this.customer[key] = obj[key];
        //  })
        //}
        // 单独处理字段不对应的数据
        this.customer.taskId = obj.taskId;
        this.customer.customerId = obj.id
        this.customer.customerName = obj.name
      } else {
        this.customer = {
          customerId: null,
          customerName: null,
          taskId: null
        }
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleRowClick(row) {
      const customerId = row.id
      if (customerId) {
        // 单独处理字段不对应的数据
        this.customer.taskId = row.taskId;
        this.customer.customerId = row.id
        this.customer.customerName = row.name
      } else {
        this.customer = {
          customerId: null,
          customerName: null,
          taskId: null
        }
      }
    },

  }
}
;
</script>
<style scoped>
.messageCard {
  overflow-x: hidden;
  overflow-y: scroll;
  word-break: break-all;
  max-height: 100px;
  text-align: left;
  width: 350px;
  float: left;
  text-align: left;
  text-overflow: ellipsis;
  color: #313131;
}

.messageCard::-webkit-scrollbar {
  width: 4px;
}

.messageCard::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.2);
}

.messageCard::-webkit-scrollbar-track {
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}

.serve-person {
  .serve-person-form-item {
    position: relative;
    padding-left: 32px;
    border-left: 1px solid #E3E6E5;
    display: flex;

    &::before {
      content: "";
      width: 20px;
      height: 1px;
      background: #E3E6E5;
      position: absolute;
      left: 0;
      top: 16px;
    }

    &:last-child {
      border: none;

      &::after {
        content: "";
        width: 550px;
        height: 16px;
        border-left: 1px solid #E3E6E5;
        position: absolute;
        left: 0;
        top: 0;
      }
    }

    .item-op-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 20px;
      height: 32px;
      cursor: pointer;

      .item-delete-icon {
        width: 16px;
        height: 16px;
      }
    }
  }

  .add-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80px;
    height: 32px;
    border-radius: 4px;
    border: 1px solid #E3E6E5;
    cursor: pointer;
    user-select: none;

    .add-btn-icon {
      width: 16px;
      height: 16px;
    }

    .add-btn-text {
      margin-left: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
    }
  }
}
</style>
